//
//  ShareWX.swift
//  BMWShareSDK
//
//  Created by Li Shengbing, (Shengbing.Li@partner.bmw.com) on 2019/6/11.
//  Copyright © 2019年 Li Shengbing, (Shengbing.Li@partner.bmw.com). All rights reserved.
//  // 微信：https://www.jianshu.com/p/33bd30cdeb2f
//  微信分享功能不告知成功和取消操作 https://open.weixin.qq.com/cgi-bin/announce?action=getannouncement&key=11534138374cE6li&version=&lang=zh_CN&token=



import UIKit


class ShareWX: NSObject {
    
    public static let shareInstance: ShareWX = ShareWX()
    
    
    /// Share WX Req
    ///
    /// - Parameters:
    ///   - type: BMWShareType
    ///   - toWhere: WXScene?
    /// - Returns: BaseReq
    static func share(type: ShareWXType, platform: WXScene? = WXSceneTimeline) {
        
        let message = WXMediaMessage()
        let req = SendMessageToWXReq()
        let to = platform == nil ? WXSceneTimeline : platform!
        req.scene = Int32(to.rawValue)
        req.bText = false
        
        switch type {
        case .textOnly(text: let title):
            assert(title.count != 0, "\"===== share to wx with text can't be empty! =====\"")
            req.bText = true
            req.text = title
            
        case .imageOnly(image: let _image):
            if _image == nil {
                assert(false, "\"===== share to wx with image can't set nil =====\"")
            }
            let ext = WXImageObject()
            ext.imageData = _image?.pngData() ?? Data()
            message.mediaTagName = "myBmwPicture"
            
            let resultImage = _image?.compresseImageSize(size: CGSize(width: 100, height: 100))
            message.thumbData = resultImage?.pngData()
            message.mediaObject = ext
            
        case .urlLink(text: let _text, description: let _description, image: let _image, url: let _url):
            if _url == nil || (_url ?? "").count == 0 {
                assert(false , "\"===== url string can't set nil, and can't be empty =====\"")
            }
            message.title = _text ?? ""
            message.description = _description ?? ""
            message.setThumbImage(_image ?? UIImage())
            let ext = WXWebpageObject()
            ext.webpageUrl = _url ?? ""
            message.mediaObject = ext
            
        case .audio(text: let _title, description: let _description ,audioUrl: let _audioUrl, audioDataUrl: let _audioDataUrl):
            message.title = _title ?? ""
            message.description = _description ?? ""
            let ext = WXMusicObject()
            ext.musicUrl = _audioUrl
            ext.musicDataUrl = _audioDataUrl ?? ""
            message.mediaObject = ext
            
        case .vedio(text: let _text, description: let _description, image: let _image, vedioUrl: let _videoUrl, vedioLowBandUrl: let _vedioLowBandUrl):
            message.title = _text ?? ""
            message.description = _description ?? ""
            message.setThumbImage(_image ?? UIImage())
            
            let ext = WXVideoObject()
            ext.videoUrl = _videoUrl
            ext.videoLowBandUrl = _vedioLowBandUrl ?? ""
            message.mediaObject = ext
            
        case .file(text: let _text, description: let _description, image: let _image, fileData: let _fileData):
            message.setThumbImage(_image ?? UIImage())
            message.title = _text ?? ""
            message.description = _description ?? ""
            let ext = WXFileObject()
            ext.fileData = _fileData ?? Data()
            message.mediaObject = ext
        }
        
        req.message = message
        WXApi.send(req)
    }
}

extension ShareWX: WXApiDelegate {
    public func onResp(_ resp: BaseResp) {
        if resp.isKind(of: SendMessageToWXResp.classForCoder()) {
            let sendMessageResp = resp as! SendMessageToWXResp
            /// 微信成功和取消都是返回成功、微信官网调整不返回分享结果信息
            /// https://open.weixin.qq.com/cgi-bin/announce?action=getannouncement&key=11534138374cE6li&version=&lang=zh_CN&token=
            var result: String = ""
            switch sendMessageResp.errCode {
            case WXSuccess.rawValue:
                
                result = BMWNSLocalizedString.localizedString("SHARE_WX_CALLBACK_WXSUCCESS", comment: "Shared")
            case WXErrCodeCommon.rawValue:
                result = BMWNSLocalizedString.localizedString("SHARE_WX_CALLBACK_WXERRCODECOMMON", comment: "Common error code")
            case WXErrCodeUserCancel.rawValue:
                result = BMWNSLocalizedString.localizedString("SHARE_WX_CALLBACK_WXERRCODEUSERCANCEL", comment: "User clicked cancel and returned")
            case WXErrCodeSentFail.rawValue:
                result = BMWNSLocalizedString.localizedString("SHARE_WX_CALLBACK_WXERRCODESENTFAIL", comment: "Failed to send to WeChat")
            case WXErrCodeAuthDeny.rawValue:
                result = BMWNSLocalizedString.localizedString("SHARE_WX_CALLBACK_WXERRCODEAUTHDENY", comment: "Authorization Failed")
            case WXErrCodeUnsupport.rawValue:
                result = BMWNSLocalizedString.localizedString("SHARE_WX_CALLBACK_WXERRCODEUNSUPPORT", comment: "WeChat is unsupported")
            default:
                break
            }
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25, execute: {
                if BMWShareManager.shareComplete != nil {
                    BMWShareManager.shareComplete!(result)
                }
            })
        }
    }
}

public enum ShareWXType {
    /// Only share text
    case textOnly(text: String)
    
    /// Only share image
    case imageOnly(image: UIImage?)
    
    /// Share url link
    case urlLink(text: String?, description: String?, image: UIImage?, url: String?)
    
    /// Share audio
    case audio(text: String?, description: String?, audioUrl: String, audioDataUrl: String?)
    
    /// Share vedio
    case vedio(text: String?, description: String?, image: UIImage?, vedioUrl: String, vedioLowBandUrl: String?)
    
    /// Share file
    case file(text: String?, description: String?, image: UIImage?, fileData: Data?)
}
